package com.shishuo.cms.filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.shishuo.cms.entity.GoodsItemEntity;
import com.shishuo.cms.service.ConfigService;
import com.shishuo.cms.service.GoodsItemService;
import com.shishuo.cms.util.ImageUtil;

public class PictureInterceptor implements HandlerInterceptor
{

	@Autowired
	private GoodsItemService goodsItemService;
	@Autowired
	private ConfigService configService;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String actionName=request.getRequestURI();
		String basePath = request.getSession().getServletContext().getRealPath("/");
		File file = new File(basePath+actionName);
		if (!file.exists()&&actionName.contains("_")) {//这里只针对要下载的图片进行处理
			if (!downLoadImg(actionName,basePath+actionName,basePath)) {
				actionName = "/"+getTemplatePath()+"images/404.jpg";
			}
			request.getRequestDispatcher(actionName).forward(request,
					response);
			response.flushBuffer();
			return false;
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	public String getTemplatePath() throws Exception
	{
		return "template/" + configService.getConfigByKey("SYS_THEME")+"/" ;
	}
	/**
	 * 自动下载图片
	 * 
	 * @param actionName
	 * @return
	 * @throws Exception
	 */
	public boolean downLoadImg(String actionName, String saveImgPath,String basePath)
																		throws Exception
	{
		String[] goodsAliasAndId = actionName.replace(".jpeg", "").split("_");
		if (goodsAliasAndId.length >= 2)
		{
			long id = Long.parseLong(goodsAliasAndId[1]);
			GoodsItemEntity goodsItemEntity = goodsItemService.getById(id);
			if (null != goodsItemEntity
				&& goodsItemEntity.getProductPicUrl() != null)
			{
				String saveImgPathNew=saveImgPath+".jpg";
				if (goodsItemEntity.getProductPicUrl().startsWith("/"))
				{
					return removePic(basePath+goodsItemEntity.getProductPicUrl(), saveImgPath);
				}
				int byteread = 0;
				URL url = null;
				URLConnection conn = null;
				InputStream inStream = null;
				try
				{
					url = new URL(goodsItemEntity.getProductPicUrl());
					conn = url.openConnection();
					inStream = conn.getInputStream();
					File file = new File(saveImgPathNew);
					if (!file.getParentFile().exists())
					{
						makeDir(file.getParentFile());
					}
					FileOutputStream fs = new FileOutputStream(saveImgPathNew);
					byte[] buffer = new byte[1204];
					while ((byteread = inStream.read(buffer)) != -1)
					{
						fs.write(buffer, 0, byteread);
					}
					inStream.close();
					fs.close();
					//压缩图片
					ImageUtil.scale2(saveImgPathNew, saveImgPath, 300, 300, true);
					return true;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				finally
				{

				}
			}
		}
		return false;
	}


	/**
	 * 
	 */
	private boolean removePic(String productPicUrl, String saveImgPath)
	{
		try
		{
			String saveImgPathNew=saveImgPath+".jpg";
			int byteread = 0;
			File oldfile = new File(productPicUrl);
			if (oldfile.exists())
			{ //文件存在时 
				InputStream inStream = new FileInputStream(productPicUrl); //读入原文件 
				FileOutputStream fs = new FileOutputStream(saveImgPathNew);
				byte[] buffer = new byte[1024];
				while ((byteread = inStream.read(buffer)) != -1)
				{
					fs.write(buffer, 0, byteread);
				}
				fs.close();
				inStream.close();
				ImageUtil.scale2(saveImgPathNew, saveImgPath, 300, 300, true);
				return true;
			}
			return false;
		}
		catch (Exception e)
		{
			System.out.println("复制单个文件操作出错");
			e.printStackTrace();

		}
		return false;
	}

	public static void makeDir(File dir)
	{
		if (!dir.getParentFile().exists())
		{
			makeDir(dir.getParentFile());
		}
		dir.mkdir();
	}
}
